# -*- coding: utf-8 -*-
import time

from src.jianghu.ThreadCarry import Carry
from src.jianghu.ThreadCheck import Check
from src.jianghu.ThreadIdle import Idle
from src.jianghu.ThreadSup import Sup
from src.conf.conf import getConf
from . import JiangHu


class FalseObj(object):
    def __init__(self):
        self.flag=False

    def is_alive(self):
        return self.flag


class Main(JiangHu.JiangHu):
    def __init__(self, thread_id, name, index, public_data,ignore_block):
        super().__init__(thread_id, name, index, public_data,ignore_block)
        self.logId=-1
        self.dm.Reg(public_data["系统"]["注册码"],public_data["系统"]["附加码"])
        self.dmVersion = self.dm.Ver()
        self.log.info("大漠版本 " + self.dmVersion)
        self.data={
            "本次开始时间":999999999999.0
        }
        self.game_thread = None
        self.check_thread = None
        x, y = self.publicData["系统"]["窗口位置"].split(",")
        self.x1 = int(x)
        self.y1 = int(y)
        self.x2 = self.x1+1280
        self.y2 = self.y1+720
        self.flag="RUNNING"
    def HandleFlag(self,value):
        if value=="RUNNING":
            if self.flag=="PAUSE":
                self.game_thread.CustomGoOn()
                self.check_thread.CustomGoOn()
                self.game_thread.dm.EnableBind(1)
                self.check_thread.dm.EnableBind(1)


            self.flag=value
        elif value=="PAUSE":
            # self.flag=value
            # try:
            #     try:
            #         res=self.game_thread.dm.EnableBind(5)
            #         self.log.info(res)
            #         self.game_thread.CustomPause()
            #     except SystemExit:
            #         self.log.info("调用Pause暂停game运行")
            #     try:
            #         res=self.check_thread.dm.EnableBind(5)
            #         self.log.info(res)
            #         self.check_thread.CustomPause()
            #     except SystemExit:
            #         self.log.info("调用Pause暂停check运行")
            #     self.flag=value
            # except AttributeError as e:
            #     print("等带游戏启动后再暂停")
            self.flag = value
            try:
                try:
                    res = self.game_thread.dm.EnableBind(5)
                    self.log.info(res)
                    res = self.check_thread.dm.EnableBind(5)
                    self.log.info(res)
                    self.game_thread.CustomPause()
                    self.check_thread.CustomPause()
                except SystemExit:
                    self.log.info("调用Pause暂停运行")
            except AttributeError as e:
                print("等带游戏启动后再暂停")
        elif value=="STOP":
            self.game_thread.Stop()
            self.check_thread.Stop()
            for i in range(30):
                self.log.info("第%s等待结束"%i)
                if self.game_thread.is_alive is False and self.check_thread.is_alive is False:
                    break
            self.flag = value




    def run(self):

        self.log.info("游戏程启动")
        while True:
            if self.flag == "WAIT" or self.flag == "PAUSE":
                self.log.info("main当前状态%s"%self.flag)
                time.sleep(1)
                continue
            if self.flag == "STOP" :
                self.log.info("main当前状态%s"%self.flag)
                break
            try:
                self.log.info(time.time())
                # 开始截图
                self.dm.DebugScreen(r"debug\debug", x1=self.x1, y1=self.y1, x2=self.x2, y2=self.y2)
                self.Process()
                time.sleep(10)
                self.Process()
                time.sleep(10)
            except SystemExit:
                self.log.info("调用stop终止运行")
                break
            except BaseException:
                self.LogTraceback()
        self.dm.UnBindWindow()
    def Process(self):


        # 判断是否开始一局新的对局
        start_game=False
        if self.game_thread is None and self.check_thread is None:
            start_game=True
        elif (self.game_thread.is_alive() is False) and (self.check_thread.is_alive() is False):
            start_game=True
        if start_game:
            self.logId += 1
            # 刷新配置文件
            self.publicData=getConf(self.logId)
            self.log.info(self.logId)
            self.log.info(self.publicData)
            self.log.info("开第%s次始启动dota2 日志id %s" % (self.logId, self.logId))
            self.data["本次开始时间"] = time.time() # todo 辅助需要单独定义
            self.log.info("本次开始时间%s" % self.data["本次开始时间"])
            self.publicData["系统"]["主要阶段"] = ""
            self.log.info("主要阶段 " + self.publicData["系统"]["主要阶段"])

            # 主动关闭dota2
            if self.publicData["系统"]["多少局重启一次dota2"] !=0 and self.logId!=0 :
                dota2_hwnd = self.dm.FindWindow(self.publicData["dota2_class_name"], self.publicData["dota2_tittle"])
                if self.logId%self.publicData["系统"]["多少局重启一次dota2"]==0 and dota2_hwnd!=0:
                    self.log.info("防止崩溃 重启dota2")
                    if dota2_hwnd!=0:
                        self.dm.SetWindowState(dota2_hwnd,0)
                        time.sleep(20)
            self.log.info("aaaaa")
            self.check_thread = Check(self.logId, "check", self.logId, self.publicData,True)
            self.publicData["obj"]["check"]= self.check_thread
            self.log.info("bbb")
            time.sleep(3)
            if self.publicData["基础配置"]["角色"] == "主c":
                self.game_thread = Carry(self.logId, "game", self.logId, self.publicData, False)
            elif self.publicData["基础配置"]["角色"] == "混子":
                self.game_thread = Idle(self.logId, "game", self.logId, self.publicData, False)
            elif self.publicData["基础配置"]["角色"] == "辅助":
                self.game_thread = Sup(self.logId, "game", self.logId, self.publicData, False)
            self.publicData["obj"]["game"] = self.game_thread
            self.log.info("ccccc")
            time.sleep(1)
            self.game_thread.start()
            self.log.info("ddddd")
            time.sleep(1)
            self.check_thread.SetSubThread(self.game_thread)
            self.check_thread.start()
            self.log.info("zzzzzz")
            time.sleep(1)
            time.sleep(120)

        self.FixSandBoxErr()
        self.FixDota2Err()
        self.log.info("本局时间%s s" % (time.time() - self.data["本次开始时间"]))
        if self.publicData["基础配置"]["角色"] != "主c":
            if self.publicData["系统"]["主要阶段"] =="进入房间" and (time.time() - self.data["本次开始时间"]) >600.0 :
                self.data["本次开始时间"]=time.time()
            if self.publicData["系统"]["主要阶段"] in ["人物选择","分解"]:
                self.data["本次开始时间"]=time.time()

        self.log.info("本局时间%s s"%(time.time() - self.data["本次开始时间"]))
        if time.time() - self.data["本次开始时间"] >self.publicData["基础配置"]["单局超时时间"] or self.publicData["是否需要重启"]:
            self.log.info("超时重起游戏对局")
            for i in range(3):
                self.log.info(i)
                self.log.info(self.game_thread.is_alive())
                self.log.info(self.check_thread.is_alive())
                if self.game_thread.is_alive():
                    self.game_thread.Stop()  # 强制杀线程
                if self.check_thread.is_alive():
                    self.check_thread.Stop()
                if self.check_thread.is_alive() is False and  self.game_thread.is_alive() is False:
                    break

            dota2_hwnd = self.dm.FindWindow(self.publicData["dota2_class_name"], self.publicData["dota2_tittle"])
            if dota2_hwnd!=0:
                self.dm.SetWindowState(dota2_hwnd, 0)
                time.sleep(20)
            time.sleep(5)
            self.publicData["是否需要重启"]=False
        if self.game_thread !=0 and self.check_thread!=0:
            self.log.info(self.game_thread.is_alive())
            self.log.info(self.check_thread.is_alive())
        dota2_hwnd= self.dm.FindWindow(self.publicData["dota2_class_name"], self.publicData["dota2_tittle"])
        self.log.info(dota2_hwnd)
        self.log.info(time.time())
        self.log.info(self.data["本次开始时间"])
        if dota2_hwnd==0:
            # 会有偶现白屏 获取不到句柄
            time.sleep(3)
            dota2_hwnd = self.dm.FindWindow(self.publicData["dota2_class_name"], self.publicData["dota2_tittle"])
            if dota2_hwnd==0 and ( time.time() - self.data["本次开始时间"] >300.0):
                if self.game_thread.is_alive():
                    self.game_thread.Stop()  # 强制杀线程
                if self.check_thread.is_alive():
                    self.check_thread.Stop()
                time.sleep(10)

    def FixDota2Err(self):
        err_hwnd = self.dm.FindWindow("#32770", "<错误> 插件版本:%s" % self.dmVersion)
        if err_hwnd<=0:
            return
        self.log.info("游戏崩溃退出")
        self.dm.SetWindowState(err_hwnd, 1)
        self.dm.DebugScreen(r"debug\error", x1=self.x1, y1=self.y1, x2=self.x2, y2=self.x2)
        self.modifyStage(main_stage="退出游戏")
        i = 0
        while i < 10:
            i = i + 1
            self.log.info("第 %s 次处理错误" % i)
            err_hwnd = self.dm.FindWindow("#32770", "<错误> 插件版本:%s" % self.dmVersion)
            self.log.info("错误创窗口句柄 %s" % err_hwnd)
            if err_hwnd > 0:
                if self.game_thread.is_alive():
                    self.log.info("开始杀死游戏线程")
                    self.game_thread.Stop()  # 强制杀线程
                if self.check_thread.is_alive():
                    self.log.info("开始杀死巡检线程")
                    self.check_thread.Stop()
                dota2_hwnd = self.dm.FindWindow(self.publicData["dota2_class_name"],
                                                self.publicData["dota2_tittle"])
                if dota2_hwnd != 0:
                    self.dm.SetWindowState(dota2_hwnd, 0)
                    time.sleep(20)
                time.sleep(3)
            err_hwnd = self.dm.FindWindow("#32770", "<错误> 插件版本:%s" % self.dmVersion)
            self.log.info("错误创窗口句柄 %s" % err_hwnd)
            if err_hwnd > 0:
                i = 0
                err_button_hwnd = self.dm.FindWindowEx(err_hwnd, "Button", "确定")
                res = self.dm.BindWindowEx(err_button_hwnd, self.publicData["系统"]["绑定模式"])
                self.log.info("绑定错误弹窗结果 %s : %s" % (res[0], res[1]))
                self.dm.LeftClick(2, 2, 2)
                self.dm.UnBindWindow()
            time.sleep(1)
        self.log.info("等待120s")
        time.sleep(120)

    # 处理沙盒相关报错
    def FixSandBoxErr(self):
        err_hwnd = self.dm.FindWindow("#32770",
                                      "[#] [%s] Low Available Memory [#]" % self.publicData["系统"]["沙盒名称"])
        if err_hwnd > 0:
            self.log.info("游戏低内存弹窗句柄 %s" % err_hwnd)
            err_button_hwnd = self.dm.FindWindowEx(err_hwnd, "Button", "OK")
            res = self.dm.BindWindowEx(err_button_hwnd, "前台")
            self.log.info("绑定错误弹窗结果 %s : %s" % (res[0], res[1]))
            self.dm.LeftClick(2, 2, 2)
            self.dm.UnBindWindow()
            time.sleep(1)
            self.log.info("等待30s")
            time.sleep(30)
        # 沙盒报错？
        err_hwnd = self.dm.FindWindow("#32770", "[#] [%s] Error [#]" % self.publicData["系统"]["沙盒名称"])

        if err_hwnd > 0:
            self.log.info("游戏沙盒报错弹窗句柄 %s" % err_hwnd)
            err_button_hwnd = self.dm.FindWindowEx(err_hwnd, "Button", "OK")
            res = self.dm.BindWindowEx(err_button_hwnd, "前台")
            self.log.info("绑定错误弹窗结果 %s : %s" % (res[0], res[1]))
            self.dm.LeftClick(2, 2, 2)
            self.dm.UnBindWindow()
            time.sleep(1)
            self.log.info("等待30s")
            time.sleep(10)
